const BaseRest = require('./base.js');

module.exports = class extends BaseRest {
  /**
     * 获取配置
     * @return {[type]} [description]
     */
  async getAction() {
    let data;
    if (this.id) {
      const row = await this.modelInstance.where({ name: this.id }).find();

      data = JSON.parse(row.value);
      return this.success(data);
    }

    const type = this.get('type');
    const list = await this.model('config').getList(type);
    return this.success(list);
  }

  /**
     * 更新配置
     * @return {[type]} [description]
     */
  async putAction() {
    // const name = this.get('type');
    const name = this.id;

    const value = this.post();
    think.logger.debug(value);

    // 只允许更新value
    const item = await this.modelInstance.where({ name: name }).find();
    // think.logger.debug(item);

    if (think.isEmpty(item)) {
      return this.fail(1000, '指定的配置项目不存在');
    } else {
      const res = await this.modelInstance.save(name, value);
      if (res) {
        await this.hook('configUpdate', { name: name, value: value });
        return this.success({ id: res }, '更新成功');
      } else {
        return this.fail(1000, '更新失败');
      }
    }
  }
};
